//
//  LSDetailViewController.m
//  LibraryStorm
//
//  Created by Enel@Lightning on 3/26/14.
//  Copyright (c) 2014 3ATeam. All rights reserved.
//

#import <MessageUI/MessageUI.h>
#import "LSDetailViewController.h"
#import "LSEpubViewController.h"

#import "LSCoreDataController.h"
#import "BookDetail.h"
#import "BookCategory.h"

#import "LSDownloadManager.h"
#import "AFDownloadRequestOperation.h"
#import "UIImageView+AFNetworking.h"

#import "DACircularProgressView.h"
#import "UIColor+HexString.h"
#import "CMPopTipView.h"

#import "LSSortTableView.h"
#import "LSBookGridCell.h"

static NSString * const GridCellIdentifier = @"GridCellId";
@interface LSDetailViewController () <LSDownloadManagerDelegate, UITableViewDelegate, CMPopTipViewDelegate, MFMailComposeViewControllerDelegate>

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSArray *relatedBooks;
@property (strong, nonatomic) BookDetail *book;
@property (strong, nonatomic) CMPopTipView *popTipView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *collectionViewFlowLayout;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) IBOutlet UILabel *authorLabel;
@property (weak, nonatomic) IBOutlet UITextView *summaryTextView;
@property (weak, nonatomic) IBOutlet UIButton *startButton;
@property (weak, nonatomic) IBOutlet UIImageView *downloadedIconImageView;
@property (weak, nonatomic) IBOutlet DACircularProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIButton *favoriteButton;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end

@implementation LSDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // TODO: Get bookDetail with managedObjectId which sended from mainViewController
    self.managedObjectContext = [[LSCoreDataController sharedInstance] newManagedObjectContext];
    self.book = (BookDetail *)[self.managedObjectContext objectWithID:self.managedObjectId];
    
    // TODO: Get 10 books on category
    NSString *categoryId = nil;
    if ([(NSArray *)self.book.categoryIds count] > 0) {
        categoryId = [(NSArray *)self.book.categoryIds objectAtIndex:0];
    }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categoryId = %d", [categoryId intValue]];
    BookCategory *category = (BookCategory *)[BookCategory findObjectInContext:self.managedObjectContext withPredicate:predicate];
    if (category) {
        int randomIndex = arc4random_uniform([category.listOfBooks.allObjects count]);
        self.relatedBooks = [category.listOfBooks.allObjects subarrayWithRange:NSMakeRange(randomIndex, category.listOfBooks.allObjects.count - randomIndex > 5 ? 5 : category.listOfBooks.allObjects.count - randomIndex)];
    }
    
    
    // Do any additional setup after loading the view.
    [self setListBarItem:@[@(BarItemButton_Back),@(BarItemButton_Share)]];
    
    // Set book data on view
    [self setBookDetailView];
    // Change font size, title ...
    [self customizeAppearance];
    [LSDownloadManager sharedInstance].delegate = self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.collectionView.collectionViewLayout invalidateLayout];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.popTipView dismissAnimated:YES];
    self.popTipView = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([[segue identifier] isEqualToString:@"showEpudReaderFromDetailId"]) {
        UINavigationController *navigationViewController = [segue destinationViewController];
        if ([navigationViewController.topViewController isKindOfClass:[LSEpubViewController class]]) {
            LSEpubViewController *epubViewController = (LSEpubViewController *)navigationViewController.topViewController;
            if (self.book.downloadStatus.intValue == LSObjectDownloadCompleted && self.book.bookPath.length > 0) {
                NSString *documentPath = [kAppDelegate applicationDocumentsDirectory].relativePath;
                NSString *ebookPath = [documentPath stringByAppendingFormat:@"%@", self.book.bookPath];
                epubViewController.filePath = ebookPath;
            }
        }
    }
}

#pragma mark - Customize Appearance Of DetailView
- (void)customizeAppearance
{
    self.nameLabel.font = Roboto_Bold(IS_DEVICE_IPAD ? 22 : 15);
    self.authorLabel.font = Roboto_Regular(IS_DEVICE_IPAD ? 20 :14);
    self.summaryTextView.font = Roboto_Regular(IS_DEVICE_IPAD ? 20 :14);
    self.startButton.titleLabel.font = Roboto_Bold(IS_DEVICE_IPAD ? 22 :15);
    [self.startButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.startButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [self.startButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
    self.progressView.roundedCorners = YES;
    self.progressView.progressTintColor = [UIColor colorWithHexString:Color_Orange_View];
    self.progressView.trackTintColor = [UIColor lightGrayColor];
    [self.coverImageView setClipsToBounds:YES];
}

#pragma mark - Show book on detailView
- (void)setBookDetailView
{
    if (self.book) {
        [self.coverImageView setImageWithURL:[NSURL URLWithString:self.book.coverImage] placeholderImage:BOOK_COVER_IMAGE];
        self.nameLabel.text = self.book.name;
        self.authorLabel.text = self.book.author;
        self.summaryTextView.text = self.book.summary;
        
        // Update title of button, show/hide icon downloaded, progressView
        NSString *startText = nil;
        self.downloadedIconImageView.hidden = YES;
        self.progressView.hidden = YES;
        switch (self.book.downloadStatus.intValue) {
            case LSObjectDownloadCompleted:
                self.downloadedIconImageView.hidden = NO;
                startText = NSLocalizedString(@"ReadEbook", nil);
                if (!self.book.bookPath && self.book.bookPath.length == 0) {
                    self.downloadedIconImageView.hidden = YES;
                    startText = NSLocalizedString(@"DownloadEbook", nil);
                    [self updateCurrentBookDownloadStatus:LSObjectDownloadFailed buttonText:startText withOperation:nil];
                }
                break;
            case LSObjectDownloadFailed:
            case LSObjectDownloadNone:
                startText = NSLocalizedString(@"DownloadEbook", nil);
                break;
                
            case LSObjectDownloading:
                self.progressView.hidden = NO;
                startText = NSLocalizedString(@"Downloading", nil);
                break;
                
            case LSObjectDownloadPause:
                self.progressView.hidden = NO;
                startText = NSLocalizedString(@"Resume", nil);
                break;
            default:
                break;
        }
        
        [self.startButton setTitle:startText forState:UIControlStateNormal];
        [self.favoriteButton setImage:self.book.favorited.boolValue?BOOK_LIKED_IMAGE:BOOK_UNLIKED_IMAGE forState:UIControlStateNormal];
    }
}

#pragma mark - Target Action
- (IBAction)startReadingBook:(id)sender
{
    if (![kAppDelegate fbSession].isOpen) {
        LSAlert(NSLocalizedString(@"AlertTitle", nil), NSLocalizedString(@"LoginFacebookRequired", nil));
        return;
    }
    NSString *startText = nil;
    LSObjectDownloadStatus downloadStatus = LSObjectDownloadNone;
    switch (self.book.downloadStatus.intValue) {
        case LSObjectDownloadCompleted:
        {
            if (self.book.bookPath && self.book.bookPath.length > 0) {
                // Start reading Ebook
                downloadStatus = LSObjectDownloadCompleted;
                startText = NSLocalizedString(@"ReadEbook", nil);
                [self performSegueWithIdentifier:@"showEpudReaderFromDetailId" sender:sender];
                [self.book setObjectInContext:self.managedObjectContext withValue:[NSDate date] forKey:@"recentAt"];
            }else {
                // Download Failed
                self.downloadedIconImageView.hidden = YES;
                downloadStatus = LSObjectDownloadFailed;
                startText = NSLocalizedString(@"DownloadEbook", nil);
            }
        }
            break;
            
        case LSObjectDownloadFailed:
        case LSObjectDownloadNone:
        {
            // Start downloading Ebook
            if (self.book.downloadLink.length > 0) {
                
                NSURL *ebookURL = [[kAppDelegate applicationDocumentsDirectory] URLByAppendingPathComponent:@"Ebook"];
                NSError *error = nil;
                if (![[NSFileManager defaultManager] fileExistsAtPath:ebookURL.relativePath]) {
                    [[NSFileManager defaultManager] createDirectoryAtPath:ebookURL.relativePath withIntermediateDirectories:NO attributes:nil error:&error];
                }
                NSURL *downloadEbookURL = [NSURL URLWithString:self.book.downloadLink];
                AFDownloadRequestOperation *operation = [[LSDownloadManager sharedInstance] addURL:downloadEbookURL fileStorePath:ebookURL.relativePath];
                [[LSDownloadManager sharedInstance] setupDownloadOperation:operation];
                [[LSDownloadManager sharedInstance] startOperation:operation];
                
                self.progressView.hidden = NO;
                startText = NSLocalizedString(@"Downloading", nil);
                downloadStatus = LSObjectDownloading;
            }else {
                startText = NSLocalizedString(@"DownloadEbook", nil);
            }
        }
            break;
            
        case LSObjectDownloading:
        {
            // If ebook downloading, user click button that Pause downloading and change status
            if (self.book.downloadLink.length > 0) {
                NSURL *downloadEbookURL = [NSURL URLWithString:self.book.downloadLink];
                BOOL isPause = [[LSDownloadManager sharedInstance] pauseOperationWithURL:downloadEbookURL];
                
                if (isPause) {
                    self.progressView.hidden = NO;
                    startText = NSLocalizedString(@"Resume", nil);
                    downloadStatus = LSObjectDownloadPause;
                }else {
                    self.progressView.hidden = YES;
                    startText = NSLocalizedString(@"DownloadEbook", nil);
                    downloadStatus = LSObjectDownloadFailed;
                }
            }
        }
            break;
            
        case LSObjectDownloadPause:
        {
            // When user click button so that resume downloading ebook
            if (self.book.downloadLink.length > 0) {
                NSURL *downloadEbookURL = [NSURL URLWithString:self.book.downloadLink];
                BOOL isResume = [[LSDownloadManager sharedInstance] startOperationWithURL:downloadEbookURL];
                
                if (isResume) {
                    self.progressView.hidden = NO;
                    startText = NSLocalizedString(@"Downloading", nil);
                    downloadStatus = LSObjectDownloading;
                }else {
                    self.progressView.hidden = YES;
                    startText = NSLocalizedString(@"DownloadEbook", nil);
                    downloadStatus = LSObjectDownloadFailed;
                }
            }
        }
            break;
        default:
            break;
    }
    
    [self updateCurrentBookDownloadStatus:downloadStatus buttonText:startText withOperation:nil];
}

- (IBAction)changeFavoriteStatusOfBook:(id)sender
{
    [self.book setObjectInContext:self.managedObjectContext withValue:[NSNumber numberWithBool:!self.book.favorited.boolValue] forKey:@"favorited"];
    [self.favoriteButton setImage:self.book.favorited.boolValue?BOOK_LIKED_IMAGE:BOOK_UNLIKED_IMAGE forState:UIControlStateNormal];
}

- (void)clickShareButton:(UIButton *)sender
{
    if (!_popTipView) {
        [self.popTipView presentPointingAtView:sender inView:self.view animated:YES];
    }else {
        [self.popTipView dismissAnimated:YES];
        self.popTipView = nil;
    }
}

#pragma mark - CMPopTipView
- (CMPopTipView *)popTipView
{
    if (!_popTipView) {
        LSSortTableView *sortTableView = [[LSSortTableView alloc] initWithFrame:CGRectMake(0, 0, 200, 85)];
        sortTableView.items = @[NSLocalizedString(@"Facebook", nil),NSLocalizedString(@"Email", nil)];
        sortTableView.delegate = self;
        sortTableView.dataSource = sortTableView;
        sortTableView.selectedIndex = -1;
        sortTableView.showsHorizontalScrollIndicator = NO;
        sortTableView.showsVerticalScrollIndicator = NO;
        sortTableView.scrollEnabled = NO;
        
        _popTipView = [[CMPopTipView alloc] initWithCustomView:sortTableView];
        _popTipView.delegate = self;
        _popTipView.backgroundColor = [UIColor whiteColor];
        _popTipView.dismissTapAnywhere = YES;
        _popTipView.cornerRadius = 5.0;
        _popTipView.hasShadow = NO;
        _popTipView.has3DStyle = NO;
        _popTipView.hasGradientBackground = NO;
        _popTipView.borderColor = [UIColor colorWithHexString:Color_Orange_View];
    }
    
    return _popTipView;
}

- (void)popTipViewWasDismissedByUser:(CMPopTipView *)popTipView
{
    [self.popTipView dismissAnimated:YES];
    self.popTipView = nil;
}

#pragma mark - Rotate Orientation
/**
 * Method name: willRotateToInterfaceOrientation:duration
 * Description: Delegate called when user rotate device. Change popTipView when rotate.
 * Parameters: UIInterfaceOrientation, NSTimeInterval
 */
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self.collectionView.collectionViewLayout invalidateLayout];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    //Fix orientation of popTipView
    if (_popTipView) {
        id targetObject = self.popTipView.targetObject;
        [self.popTipView dismissAnimated:NO];
        
        if ([targetObject isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)targetObject;
            [self.popTipView presentPointingAtView:button inView:self.view animated:NO];
        }
        else {
            UIBarButtonItem *barButtonItem = (UIBarButtonItem *)targetObject;
            [self.popTipView presentPointingAtBarButtonItem:barButtonItem animated:NO];
        }
    }
}
#pragma mark - Collection view datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.relatedBooks.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // Load Grid Collection Cell
    LSBookGridCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:GridCellIdentifier forIndexPath:indexPath];
    
    if (indexPath.row < self.relatedBooks.count) {
        BookDetail *book = [self.relatedBooks objectAtIndex:indexPath.row];
        // Load content for this cell
        [cell loadContentCell:book atIndexPath:indexPath];
    }
    
    return cell;
}

#pragma mark - Colection view delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < self.relatedBooks.count) {
        self.book = [self.relatedBooks objectAtIndex:indexPath.row];
        [self setBookDetailView];
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    }
}

#pragma mark - CollectionView Flow Layout Delegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [self showCollectionViewFlowLayout:Device_Orientation];
}

- (CGSize)showCollectionViewFlowLayout:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (IS_DEVICE_IPAD) {
        if (UIDeviceOrientationIsPortrait(toInterfaceOrientation)) {
            [self collectionviewFlowLayoutWith:0.0f
                         andMinimumLineSpacing:25.0f
                             andEdgeInsetsMake:UIEdgeInsetsMake(0.0f, 35.0f, 0.0f, 35.0f)
                                   andSizeMake:CGSizeMake(150.0f, 225.0f)];
        }else {
            [self collectionviewFlowLayoutWith:0.0f
                         andMinimumLineSpacing:35.0f
                             andEdgeInsetsMake:UIEdgeInsetsMake(0.0f, 62.5f, 0.0f, 62.5f)
                                   andSizeMake:CGSizeMake(150.0f, 225.0f)];
        }
    }else {
        [self collectionviewFlowLayoutWith:0.0f
                     andMinimumLineSpacing:10.0f
                         andEdgeInsetsMake:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)
                               andSizeMake:CGSizeMake(100.0f, 141.0f)];
    }
    
    return self.collectionViewFlowLayout.itemSize;
}

- (void)collectionviewFlowLayoutWith:(float)minimumInteritemSpacing
               andMinimumLineSpacing:(float)minimumLineSpacing
                   andEdgeInsetsMake:(UIEdgeInsets)edgeInsetsMake
                         andSizeMake:(CGSize)sizeMake {
    [self.collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [self.collectionViewFlowLayout setMinimumInteritemSpacing:minimumInteritemSpacing];
    [self.collectionViewFlowLayout setMinimumLineSpacing:minimumLineSpacing];
    self.collectionViewFlowLayout.sectionInset = edgeInsetsMake;
    [self.collectionViewFlowLayout setItemSize:sizeMake];
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        // Share facebook
        // We will post on behalf of the user, these are the permissions we need:
        NSArray *permissionsNeeded = @[@"publish_actions"];
        
        // Request the permissions the user currently has
        [FBRequestConnection startWithGraphPath:@"/me/permissions"
                              completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                  if (!error){
                                      NSDictionary *currentPermissions= [(NSArray *)[result data] objectAtIndex:0];
                                      NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:@[]];
                                      
                                      // Check if all the permissions we need are present in the user's current permissions
                                      // If they are not present add them to the permissions to be requested
                                      for (NSString *permission in permissionsNeeded){
                                          if (![currentPermissions objectForKey:permission]){
                                              [requestPermissions addObject:permission];
                                          }
                                      }
                                      
                                      // If we have permissions to request
                                      if ([requestPermissions count] > 0){
                                          // Ask for the missing permissions
                                          [FBSession.activeSession requestNewPublishPermissions:requestPermissions
                                                                                defaultAudience:FBSessionDefaultAudienceFriends
                                                                              completionHandler:^(FBSession *session, NSError *error) {
                                                                                  if (!error) {
                                                                                      // Permission granted, we can request the user information
                                                                                      [self makeRequestToShareLink];
                                                                                  } else {
                                                                                      // An error occurred, handle the error
                                                                                      // See our Handling Errors guide: https://developers.facebook.com/docs/ios/errors/
                                                                                      NSLog(@"%@", error.description);
                                                                                  }
                                                                              }];
                                      } else {
                                          // Permissions are present, we can request the user information
                                          [self makeRequestToShareLink];
                                      }
                                      
                                  } else {
                                      // There was an error requesting the permission information
                                      // See our Handling Errors guide: https://developers.facebook.com/docs/ios/errors/
                                      NSLog(@"%@", error.description);
                                  }
                              }];
    }else if (indexPath.row == 1) {
        // Share email
        // You must check that the current device can send email messages before you
        // attempt to create an instance of MFMailComposeViewController.  If the
        // device can not send email messages,
        // [[MFMailComposeViewController alloc] init] will return nil.  Your app
        // will crash when it calls -presentViewController:animated:completion: with
        // a nil view controller.
        if ([MFMailComposeViewController canSendMail]) {
            [self displayMailComposerSheet];
        }
        else {
            LSAlert(NSLocalizedString(@"AlertTitle", nil), NSLocalizedString(@"MailError", nil));
        }
    }
    
    [self.popTipView dismissAnimated:YES];
    self.popTipView = nil;
}

- (void)makeRequestToShareLink
{
    // NOTE: pre-filling fields associated with Facebook posts,
    // unless the user manually generated the content earlier in the workflow of your app,
    // can be against the Platform policies: https://developers.facebook.com/policy
    
    // Put together the dialog parameters
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   self.book.name, @"name",
                                   self.book.author, @"caption",
                                   self.book.summary, @"description",
                                   @"https://www.facebook.com/pages/Tàng-Thư-Viện/304460859705018?ref=hl", @"link",
                                   @"http://pik.vn/2014d71b071b-bb20-41fa-b35d-2f93f005ec29.png", @"picture",
                                   nil];
    
    // Make the request
    [FBRequestConnection startWithGraphPath:@"/me/feed"
                                 parameters:params
                                 HTTPMethod:@"POST"
                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              if (!error) {
                                  // Link posted successfully to Facebook
                                  NSLog(@"result: %@", result);
                                  LSAlert(NSLocalizedString(@"AlertTitle", nil), NSLocalizedString(@"FacebookShareSuccessful", nil));
                              } else {
                                  // An error occurred, we need to handle the error
                                  // See: https://developers.facebook.com/docs/ios/errors
                                  NSLog(@"%@", error.description);
                                  LSAlert(NSLocalizedString(@"AlertTitle", nil), NSLocalizedString(@"FacebookShareFail", nil));
                              }
                          }];
}

#pragma mark - Download Manager Delegate
- (void)downloadManager:(LSDownloadManager *)downloadManager operationCompleted:(AFHTTPRequestOperation *)operation
{
    NSHTTPURLResponse *urlResponse = [operation response];
    if ([self.book.downloadLink isEqualToString:[urlResponse URL].absoluteString]) {
        self.progressView.hidden = YES;
        self.downloadedIconImageView.hidden = NO;
        [self updateCurrentBookDownloadStatus:LSObjectDownloadCompleted buttonText:NSLocalizedString(@"ReadEbook", nil) withOperation:operation];
    }else {
        [self changeDownloadStatus:LSObjectDownloadCompleted buttonText:nil withOperation:operation];
    }
}

- (void)downloadManager:(LSDownloadManager *)downloadManager operationFailed:(AFHTTPRequestOperation *)operation
{
    NSHTTPURLResponse *urlResponse = [operation response];
    if (operation.error.code == 516) {
        // Error File isExist
        if ([self.book.downloadLink isEqualToString:[urlResponse URL].absoluteString]) {
            self.progressView.hidden = YES;
            self.downloadedIconImageView.hidden = NO;
            [self updateCurrentBookDownloadStatus:LSObjectDownloadCompleted buttonText:NSLocalizedString(@"ReadEbook", nil) withOperation:operation];
        }else {
            [self changeDownloadStatus:LSObjectDownloadCompleted buttonText:NSLocalizedString(@"ReadEbook", nil) withOperation:operation];
        }
    }else {
        // Download Failed
        if ([self.book.downloadLink isEqualToString:[urlResponse URL].absoluteString]) {
            self.progressView.hidden = YES;
            self.downloadedIconImageView.hidden = YES;
            [self updateCurrentBookDownloadStatus:LSObjectDownloadFailed buttonText:NSLocalizedString(@"DownloadFailed", nil) withOperation:nil];
        }else {
            [self changeDownloadStatus:LSObjectDownloadFailed buttonText:nil withOperation:operation];
        }
        
        [[LSDownloadManager sharedInstance] cancelOperation:(AFDownloadRequestOperation *)operation];
    }
}

- (void)downloadManager:(LSDownloadManager *)downloadManager operationStateUpdate:(AFDownloadRequestOperation *)operation downloadProgress:(float)progress
{
    if ([downloadManager findOperationWithURL:[NSURL URLWithString:self.book.downloadLink]] == operation) {
        [self.progressView setProgress:progress animated:YES];
        
        if (self.progressView.progress >= 1.0f) {
            [self.progressView setProgress:0.f animated:YES];
        }
    }
}

- (void)changeDownloadStatus:(LSObjectDownloadStatus)downloadStatus buttonText:(NSString *)buttonText withOperation:(AFHTTPRequestOperation *)operation
{
    if (operation) {
        NSHTTPURLResponse *urlResponse = operation.response;
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"downloadLink = %@", urlResponse.URL.absoluteString];
        BookDetail *book = (BookDetail *)[BookDetail findObjectInContext:self.managedObjectContext withPredicate:predicate];
        if (book) {
            [book setObjectInContext:self.managedObjectContext withValue:[NSNumber numberWithInt:downloadStatus] forKey:@"downloadStatus"];
            if ([operation isKindOfClass:[AFDownloadRequestOperation class]]) {
                NSString *targetPath = [(AFDownloadRequestOperation *)operation targetPath];
                NSString *documentPath = [kAppDelegate applicationDocumentsDirectory].relativePath;
                if ([targetPath rangeOfString:documentPath].location != NSNotFound) {
                    NSString *bookPath = [targetPath stringByReplacingOccurrencesOfString:documentPath withString:@""];
                    [book setObjectInContext:self.managedObjectContext withValue:bookPath forKey:@"bookPath"];
                    self.changeDownloadStatusCompletionBlock();
                }
            }
        }
    }
}

- (void)updateCurrentBookDownloadStatus:(LSObjectDownloadStatus)downloadStatus buttonText:(NSString *)buttonText withOperation:(AFHTTPRequestOperation *)operation
{
    [self.book setObjectInContext:self.managedObjectContext withValue:[NSNumber numberWithInt:downloadStatus] forKey:@"downloadStatus"];
    [self.startButton setTitle:buttonText forState:UIControlStateNormal];
    if (operation) {
        if ([operation isKindOfClass:[AFDownloadRequestOperation class]]) {
            NSString *targetPath = [(AFDownloadRequestOperation *)operation targetPath];
            NSString *documentPath = [kAppDelegate applicationDocumentsDirectory].relativePath;
            if ([targetPath rangeOfString:documentPath].location != NSNotFound) {
                NSString *bookPath = [targetPath stringByReplacingOccurrencesOfString:documentPath withString:@""];
                [self.book setObjectInContext:self.managedObjectContext withValue:bookPath forKey:@"bookPath"];
                self.changeDownloadStatusCompletionBlock();
            }
        }
    }
}

#pragma mark - Compose mail
// -------------------------------------------------------------------------------
//	displayMailComposerSheet
//  Displays an email composition interface inside the application.
//  Populates all the Mail fields.
// -------------------------------------------------------------------------------
- (void)displayMailComposerSheet
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"[BookStorm] Share ebook"];
	
	// Set up recipients
//	NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"];
//	NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
//	NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"];
	
//	[picker setToRecipients:toRecipients];
//	[picker setCcRecipients:ccRecipients];
//	[picker setBccRecipients:bccRecipients];
	
	// Attach an image to the email
//	NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];
//	NSData *myData = [NSData dataWithContentsOfFile:path];
//	[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
	
	// Fill out the email body text
	NSString *emailBody = [NSString stringWithFormat:@"Name: %@\nAuthor: %@\nSummary: %@\nLink: %@", self.book.name, self.book.author, self.book.summary, self.book.downloadLink];
	[picker setMessageBody:emailBody isHTML:NO];
	
	[self presentViewController:picker animated:YES completion:NULL];
}

#pragma mark - Mail Delegate
// -------------------------------------------------------------------------------
//	mailComposeController:didFinishWithResult:
//  Dismisses the email composition interface when users tap Cancel or Send.
//  Proceeds to update the message field with the result of the operation.
// -------------------------------------------------------------------------------
- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
	NSString *message = nil;
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			message = @"Mail sending canceled";
			break;
		case MFMailComposeResultSaved:
			message = @"Mail saved";
			break;
		case MFMailComposeResultSent:
			message = @"Mail sent";
			break;
		case MFMailComposeResultFailed:
			message = @"Mail sending failed";
			break;
		default:
			message = @"Mail not sent";
			break;
	}
    
	[self dismissViewControllerAnimated:YES completion:^{
        LSAlert(NSLocalizedString(@"AlertTitle", nil), message);
    }];
}

@end
